from serial.tools import list_ports
from time import sleep
import serial

class serialPortTool(object):
    
    def __init__(self,pid_vid_info,debugPrint):
        self.serial = None
        self.serial_port = ""
        self.pid_vid_if = pid_vid_info
        self.debugprint = debugPrint
    
    def find_SerialPort(self):
        timeout = 10
        while timeout > 0:
            for p in list_ports.comports():
                if self.debugprint == 1:
                    print p[2]
                if p[2].upper().startswith(self.pid_vid_if):
                    self.serial_port = p[0]
                    if self.debugprint == 1:
                        print('INFO: Find ' +  self.pid_vid_if + ' on: ' + self.serial_port)
                    return self.serial_port
        
            sleep(0.01)
            timeout -= 1
        print("Error: No serial port found..")

    def SerialPortopen(self):
        self.serial = serial.Serial(port=self.serial_port,baudrate=115200,bytesize=8,stopbits=1,timeout=1)
#        return self.serial

    def SerialPortWrite(self,message):
        try:
            if self.debugprint == 1 :
                print "write " + message
            self.serial.write(message + '\r\n')
        except IOError as e:
            print(e)
            self.serial.close()        

    def SerialPortReadLine(self):
        return self.serial.readline().strip()
            
    def SerialPortRead(self,nTime):
        rcv_message = ""
        n = 0
        while(n<nTime):
            line = self.serial.readline().strip()
            if self.debugprint == 1:
                print line
            if line:
                rcv_message = rcv_message + line
            sleep(0.01)
            n = n+1
        return rcv_message
    
    def SerialPortRead2(self):
        END_SYSEX = 0xF7 
        received_data = []
        data = ord(self.serial.read())
        while data != END_SYSEX:
            received_data.append(data)
            data = ord(self.serial.read())
        return received_data
        
    def SerialPortReadADC(self, channel):
        done = 0
        START_SYSEX_AIN1 = 0xE3 
        START_SYSEX_AIN2 = 0xE4
        START_SYSEX_20mA = 0xE5
        received_data = []     
        while (done==0):
            data = ord(self.serial.read())
            if (((data==START_SYSEX_AIN1) and (channel==3)) or ((data==START_SYSEX_AIN2) and (channel==4)) or ((data==START_SYSEX_20mA) and (channel==5))):
                received_data.append(data)          #Fisrt byte
                data = ord(self.serial.read())
                received_data.append(data)          #Second byte
                data = ord(self.serial.read())
                received_data.append(data)          #Third byte
                done = 1
                
        return (received_data[2]<<7) + received_data[1]
        
    def flush_buffer(self):
        self.serial.flushInput()
        self.serial.flushOutput        
    
    def SerialPortClose(self):
        self.serial.close()
#----------------------------------------------------------------------#
class FixSerialPortTool(object):
    
    def __init__(self,port,debugPrint):
        self.serial = None
        self.serial_port = port
        self.debugprint = debugPrint
    

    def SerialPortopen(self):
        self.serial = serial.Serial(port=self.serial_port,baudrate=115200,bytesize=8,stopbits=1,timeout=1)
#        return self.serial

    def SerialPortWrite(self,message):
        try:
            if self.debugprint == 1 :
                print "write " + message
            self.serial.write(message + '\r\n')
        except IOError as e:
            print(e)
            self.serial.close()
            
    def SerialPortReadLine(self):
        return self.serial.readline().strip()
            
    def SerialPortRead(self,nTime):
        rcv_message = ""
        n = 0
        while(n<nTime):
            line = self.serial.readline().strip()
            if self.debugprint == 1:
                print line
            if line:
                rcv_message = rcv_message + line
            sleep(0.01)
            n = n+1
        return rcv_message
        
    def SerialPortClose(self):
        self.serial.close()        

    def SerialPortReadADC(self, channel):
        done = 0
        START_SYSEX_AIN1 = 0xE3 
        START_SYSEX_AIN2 = 0xE4
        START_SYSEX_20mA = 0xE5
        received_data = []     
        while (done==0):
            data = ord(self.serial.read())
            if (((data==START_SYSEX_AIN1) and (channel==3)) or ((data==START_SYSEX_AIN2) and (channel==4)) or ((data==START_SYSEX_20mA) and (channel==5))):
                received_data.append(data)          #Fisrt byte
                data = ord(self.serial.read())
                received_data.append(data)          #Second byte
                data = ord(self.serial.read())
                received_data.append(data)          #Third byte
                done = 1
                
        return (received_data[2]<<7) + received_data[1]
        
    def SerialPortClose(self):
        self.serial.close()        
        